#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;

void Usage(const std::string proc)
{
    cout << "\n\nUsage:" << proc << " server serverport\n" << endl;
}
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);


    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while(true)
    {
        int cnt = 5;
        bool isreconnect = false;
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0)
        {
            cerr << "sock error" << endl;
            return 1;
        }
        do
        {
            //tcp要bind,但是不用显示bind
            //客户端发起connect的时候，进行自动随机bind
            int n = connect(sockfd, (const sockaddr*)&server, sizeof(server));
            if(n < 0)
            {
                isreconnect = true;
                cnt--;
                cerr << "connect error..., reconnect: " << cnt <<  endl;
                //return 2;
                sleep(1);
            }
            else
            {
                break;
            }
        }while(cnt && isreconnect);

        if(cnt == 0)
        {
            cerr << "user offline..." << endl;
            break;
        }

        string message; 

        cout << "Please Enter# ";
        getline(cin, message);

        //sleep(10);
        int n = write(sockfd, message.c_str(), message.size());
        if(n < 0)
        {
            std::cerr << "writer error ..." << endl;
            isreconnect = true;
            continue;
        }

        //cout << message << endl;
        char inbuffer[4096];
        n = read(sockfd, inbuffer, sizeof(inbuffer));
         
        if(n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }         

        close(sockfd);
    }

    return 0;
}